package com.lanju.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lanju.model.Message;
import com.lanju.model.MessageUtil;
import com.lanju.service.impl.MessageRest;
import com.lanju.util.WeiXinUtil;

/**
 * 
 * @author zengqd
 * @CrateTime 2018年9月23日 下午4:44:41
 */
@Controller
@RequestMapping("weixinauth")
public class WeiXinAuthController {
	
	@Autowired
	MessageRest messageRest;

	/**
	 * 认证服务器
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("getWxAuth")
	public void getWxAuth(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// 设置字符集
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		// 获取输出
		PrintWriter out = resp.getWriter();
		// 接入调用方法，处理接入
		WeiXinUtil.connect(req, out);
		// 回送信息
		echoMsg(req, resp);

	}

	/**
	 * 自动回送消息，在这里dopost需要做以下的6步 1、获取xml数据
	 * 2、xml------->解析------->存放在map----->xml数据 3、xml数据解析转化成对象
	 * 4、将对象中的属性from<--->to 交换位置，更改时间，发送不同的内容 5、将对象再转为xml 6、resp发送出去
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void echoMsg(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		PrintWriter writer = resp.getWriter();
		Map<String, String> xmlMap = null;
		try {
			// 2、xml------->解析------->存放在map----->xml数据
			xmlMap = MessageUtil.toMap(req.getInputStream());
			// 3、xml数据解析转化成对象
			Message message = MessageUtil.toMessage(xmlMap);
			// 将对象中的属性from<--->to 交换位置，更改时间，发送不同的内容
			String from = message.getFromUserName();
			String to = message.getToUserName();

			message.setFromUserName(to);
			message.setToUserName(from);
			message.setCreateTime(System.currentTimeMillis());
			String content = message.getContent();
			content = null == content ? "" : content.trim();
			// 编辑返回数据
			String reply = "";

			// 获取消息类型
			String type = xmlMap.get("MsgType");
			// 比较
			if (type.equals("text")) {
				if (content.equals("1")
						|| content.equalsIgnoreCase("miniyiwei")) {
					reply = setTxt();
				} else if (content.equals("2")
						|| content.equalsIgnoreCase("yuwen")) {
					reply = setYUWEN();
				} else if (content.equals("?") || content.equals("？")) {
					reply = mainMenu();
				} else if (content.equals("管家") || content.equals("管家端")) {
					reply = "点击链接登录管家端-->  http://lanjushiye.com.cn/LanJuPublic/jsp/login.html?flag=2";
				} else {
					reply = weather(content);
				}
			} else if (type.equals("event")) {
				// 获取事件类型
				String eventType = xmlMap.get("Event").toLowerCase();
				System.out.println("eventType=="+eventType);
				if (eventType.equals("subscribe")) {
					System.out.println("有新用户啦！");
					reply = mainMenu();
					message.setMsgId("text");
				} else if (eventType.equals("unsubscribe")) {
					System.out.println("有人退出了");
				}else if (eventType.equals("click")) {
					System.out.println("回复图片");
//					Map<String, String> map = MessageUtil.parseXml(req, resp);
//					messageRest.handleMsg(req, resp, map);
					message.setContent(content);
//					message.setCreateTime(new Date().getTime());
//					message.setMsgId("1234567890123456");
//					message.setMediaId("saR98JpnunXvfthWot_KxtwJGeRHQ8sFJ3Dos196sFI");
//					message.setMsgType("image");
					String MediaId="saR98JpnunXvfthWot_KxtwJGeRHQ8sFJ3Dos196sFI";
					String xmlStr = "<xml>"
				                + "<ToUserName><![CDATA[" + message.getToUserName() + "]]></ToUserName>"
				                + "<FromUserName><![CDATA[" + message.getFromUserName() + "]]></FromUserName>"
				                + "<CreateTime>" + String.valueOf(new Date().getTime()) + "</CreateTime>"
				                + "<MsgType><![CDATA[image]]></MsgType>"
				                + "<Image>"
				                + "<MediaId><![CDATA[" + MediaId + "]]></MediaId>"
				                + "</Image>"
				                + "<MsgId>1234567890123456</MsgId> "
				                + " </xml>";
					writer.print(xmlStr);
					System.out.println("回复图片reply="+xmlStr);
					return;
				}
			}
			// 设置回送信息
			message.setContent(reply);
			// 将message对象转化为xml
			String xmlStr = MessageUtil.toXml(message);
			System.out.println(xmlStr);
			// 使用writer对象发送出去
			writer.print(xmlStr);

		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 天气查询
	 * 
	 * @param content
	 * @return
	 */
	private String weather(String content) {
		content = content.replace("市", "");
		// 获取天气字符串
		// String weatherStr= Wea
		return content;
	}

	private String setTxt() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("我是一名程序员\n");
		buffer.append("请问helloworld怎么写\n");
		return buffer.toString();
	}

	private String setYUWEN() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("我是一名老师\n");
		buffer.append("教语文的\n");
		return buffer.toString();
	}

	private String mainMenu() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("1、主菜单\n");
		buffer.append("2、新闻 ");
		return buffer.toString();
	}
	
	
//	private String 
}
